<template>
  <div class="leave-request-page">
    <!-- 步骤导航 -->
    <div class="step-nav">
      <div class="step-item active">
        <div class="step-num">1</div>
        <div class="step-text">申请请假</div>
      </div>
      <div class="step-connector"></div>
      <div class="step-item">
        <div class="step-num">2</div>
        <div class="step-text">申请审批</div>
      </div>
      <div class="step-connector"></div>
      <div class="step-item">
        <div class="step-num">3</div>
        <div class="step-text">请假审批</div>
      </div>
    </div>

    <!-- 合并为单个 el-form，统一管理验证规则 -->
    <el-form
    ref="leaveForm"
    :rules="formRules"
    :model="form"
    label-width="100px"
    class="form-wrapper"
    >
    <!-- 基本信息表单分组 -->
    <div class="form-group">
      <div class="group-header">
        <h3>基本信息</h3>
      </div>
      <div class="form-content">
        <el-form-item label="老人姓名" prop="elderName">
          <el-select v-model="form.elderName" placeholder="请选择" @change="handleElderSelect" style="width: 300px;">
            <el-option v-for="item in elderList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="老人身份证号" prop="elderIdCard">
          <el-input v-model="form.elderIdCard" placeholder="老人身份号" :disabled="true" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="form.mobile" placeholder="联系方式" :disabled="true" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="护理等级" prop="levelName">
          <el-input v-model="form.levelName" placeholder="护理等级" :disabled="true" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="入住床位" prop="bedNo">
          <el-input v-model="form.bedNo" placeholder="入住床位" :disabled="true" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="护理员" prop="nickName">
          <el-input v-model="form.nickName" placeholder="护理员" :disabled="true" style="width: 300px;"></el-input>
        </el-form-item>
      </div>
    </div>

    <!-- 申请信息表单分组 -->
    <div class="form-group">
      <div class="group-header">
        <h3>申请信息</h3>
      </div>
      <div class="form-content">
        <el-form-item label="陪同人" prop="companionType">
          <el-radio-group v-model="form.companionType">
            <el-radio label="1">家属</el-radio>
            <el-radio label="2">护理人员</el-radio>
            <el-radio label="3">其他</el-radio>
            <el-radio label="0">无</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="陪同人姓名" prop="companionName">
          <el-input v-model="form.companionName" placeholder="请输入" maxlength="10" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="陪同人联系方式" prop="companionContact">
          <el-input v-model="form.companionContact" placeholder="请输入" maxlength="11" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="请假周期" prop="leavePeriod">
          <el-date-picker
              v-model="form.leavePeriod"
              type="datetimerange"
              range-separator="-"
              start-placeholder="选择开始时间"
              end-placeholder="选择结束时间"
              @change="calculateLeaveDays"
              placeholder="请选择请假开始时间-请选择预计返回时间"
              style="width: 300px;"
              :disabled-date="disabledDate"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="请假天数" prop="leaveDays">
          <el-input v-model.number="form.leaveDays" :disabled="true" placeholder="请假天数" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="请假原因" prop="leaveReason">
          <el-input
              v-model="form.leaveReason"
              type="textarea"
              placeholder="请输入"
              maxlength="200"
              show-word-limit
              style="width: 500px;"
          ></el-input>
        </el-form-item>
      </div>
    </div>
    </el-form>

    <!-- 按钮区域 -->
    <div class="btn-group">
      <el-button @click="goBack">返回</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue';
import { useRouter } from 'vue-router';
import { addLeaveRequest, getElderInfo,getElderNameList } from "@/api/residing/leaveRequest";
import {ElMessage} from "element-plus";

// 路由实例
const router = useRouter();

const elderList = ref([]);

// 表单数据
const form = reactive({
  elderId: '',           //老人id
  elderName: '',          //老人姓名
  elderIdCard: '',        //老人身份证号
  mobile: '',             //老人联系方式
  levelName: '',          //老人护理等级
  bedNo: '',              //老人入住床位
  nickName: '',           //护理员姓名
  companionType: '1',       //陪同人类型
  companionName: '',      //陪同人姓名
  companionContact: '',   //陪同人联系方式
  leavePeriod: [],        //请假周期
  leaveDays: '',          //请假天数
  leaveReason: '',         //请假原因
});
const loading = ref(false);
// 表单验证规则
const formRules = ref({
  elderName: [{ required: true, message: '请选择老人', trigger: 'blur' }],
  companionType: [{ required: true, message: '请选择陪同人', trigger: 'blur' }],
  companionName: [{ required: true, message: '请输入陪同人姓名', trigger: 'blur' }],
  companionContact: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^[0-9]*$/, message: '手机号格式错误，请重新输入', trigger: 'blur' }
  ],
  leavePeriod: [{ required: true, message: '请选择请假周期', trigger: 'blur' }],
  leaveReason: [{ required: true, message: '请输入请假原因', trigger: 'blur' }],
});

// 表单 ref（用于手动触发表单验证）
const leaveForm = ref(null);

// 计算请假天数的方法
const calculateLeaveDays = () => {
  // 确保已选中“开始日期”和“结束日期”
  if (form.leavePeriod && form.leavePeriod.length === 2) {
    const startDate = new Date(form.leavePeriod[0]);
    const endDate = new Date(form.leavePeriod[1]);
    // 计算毫秒差
    const diffMs = endDate - startDate;
    // 转换为带小数的天数（1天 = 24*60*60*1000 毫秒）
    const daysDecimal = diffMs / (1000 * 60 * 60 * 24);
    // 核心逻辑：不足 0.5 天按 0.5 天算，不足 1 天按 1 天算，依此类推（如 0.3→0.5、0.6→1、1.2→1.5、1.8→2 等）
    const days = Math.ceil(daysDecimal * 2) / 2;
    form.leaveDays = days.toString(); // 赋值给表单字段
  } else {
    form.leaveDays = ''; // 未选全日期时清空天数
  }
};

// 禁用早于当前时间的日期
const disabledDate = (time) => {
  const now = new Date();
  now.setHours(0, 0, 0, 0); // 将当前时间重置为“当天0点0分0秒”，确保当天可选
  return time.getTime() < now.getTime();
};

// 返回按钮逻辑：跳转到请假管理页面
const goBack = () => {
  router.push({
    name: 'LeaveRequest'
  })
};

// 获取老人列表
const getElderList = async () => {
  try {
    const response = await getElderNameList();
    console.log('API返回数据:', response);
    if (response && response.code === 200 && Array.isArray(response.data)) {
      elderList.value = response.data;
      //console.log('老人列表获取成功:', elderList.value);
    } else {
      console.warn('API返回数据格式不正确');
      ElMessage.error('获取老人列表失败');
    }
  } catch (error) {
    console.error('获取老人列表失败:', error);
    ElMessage.error('获取老人列表失败');
  }
};

// 根据老人ID获取详细信息
const getElderDetail = async (elderId) => {
  try {
    loading.value = true;
    //console.log('开始获取老人详细信息，ID:', elderId);

    const res = await getElderInfo(elderId);
    console.log('老人详细信息API返回:', res);

    if (res && res.code === 200 && res.data) {
      const data = res.data;
      console.log("data:",res.data)
      // 根据后端返回的实际字段填充表单
      form.elderName = data.name || '';
      form.elderIdCard = data.idCard || '';
      form.mobile = data.mobile || '';
      form.levelName = data.levelName || '';
      form.bedNo = data.bedNo || '';
      form.nickName = data.nickName.join(',') || '';
      form.elderId = data.id || '';

      //console.log('老人详细信息填充完成:', form);
      ElMessage.success('老人信息加载成功');
    } else {
      console.warn('获取老人详情失败:', res);
      ElMessage.warning('获取老人详情失败: ' + (res.message || ''));
    }
  } catch (error) {
    console.error('获取老人详情出错:', error);
    console.error('错误详情:', error.response?.data);
    ElMessage.error('获取老人信息异常: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 选择老人时的处理
const handleElderSelect = (elderId) => {
  console.log('选择的老人ID:', elderId);
  if (elderId) {
    // 找到选中的老人信息
    const selectedElder = elderList.value.find(item => item.id === elderId);
    if (selectedElder) {
      form.elderName = selectedElder.name;
      //console.log('选中的老人:', selectedElder);
    }
    // 调用获取老人详细信息的API
    getElderDetail(elderId);
  } else {
    // 清空老人相关信息
    clearElderInfo();
  }
};

// 清空老人信息
const clearElderInfo = () => {
  form.elderName = '';
  form.elderIdCard = '';
  form.mobile = '';
  form.levelName = '';
  form.bedNo = '';
  form.nickName = '';
};

//格式化date
function formatDate(date) {
  const year = date.getFullYear();
  // 月份是 0-11，所以要 +1
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();

  // 辅助函数：给一位数的数字补零（比如 9 → "09"）
  const padZero = (num) => num.toString().padStart(2, '0');

  return `${year}-${padZero(month)}-${padZero(day)} ${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`;
}

//提交表单
const submitForm = () => {
  console.log('提交表单数据：', form);
  // 表单验证等逻辑
  //ElMessage.success('提交成功！');
  const submitData = {
    elderId: form.elderId,
    elderName: form.elderName,
    elderIdCard: form.elderIdCard,
    companionType: form.companionType,
    companionName: form.companionName,
    companionContact: form.companionContact,
    leaveStart: formatDate(form.leavePeriod[0]),
    expectedReturn: formatDate(form.leavePeriod[1]),
    leaveDays: form.leaveDays,
    leaveReason: form.leaveReason,
    nickName:form.nickName
  };
  console.log(submitData)
  addLeaveRequest(submitData).then(res => {
    if (res.code === 200) {
      ElMessage.success('请假申请提交成功');
      router.push({
        name: 'LeaveRequest', // 对应路由配置中的name
      })
    } else {
      ElMessage.error('请假申请提交失败: ' + (res.message || ''));
    }
  });
};

getElderList();


</script>

<style scoped>
.leave-request-page {
  padding: 20px;
}

/* 步骤导航样式 */
.step-nav {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30px;
}
.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  margin-left: 50px;
  margin-right: 50px;
}
.step-num {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #409eff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  margin-bottom: 8px;
}
.step-item:not(.active) .step-num {
  background-color: #dcdcdc;
}
.step-text {
  color: #606266;
  font-size: 14px;
}
.step-item.active .step-text {
  color: #409eff;
  font-weight: 500;
}
/* 步骤连接线 */
.step-connector {
  flex: 1;
  height: 1px;
  background-color: #e4e7ed;
  align-self: center;
  margin: 0 16px;
}

/* 表单分组样式 */
.form-group {
  margin-bottom: 24px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 16px;
}
.group-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
.group-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 12px;
  margin-right: 8px;
}

/* 合并后的表单容器样式 */
.form-wrapper {
  width: 600px; /* 限制整个表单宽度 */
}

/* 按钮组样式 */
.btn-group {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
.btn-group .el-button {
  margin: 0 8px;
}

/* 统一输入类组件宽度 */
.el-select, .el-input, .el-date-picker {
  width: 300px !important;
}
.el-textarea {
  width: 500px !important;
}
</style>